<?php
class Folder{
	public static function add_folder($name,$chemin,$file_type){
		$name = mysql_real_escape_string(htmlspecialchars($name));
		$chemin = mysql_real_escape_string(htmlspecialchars($chemin));
		
		$sql_query=mysql_query("Select name,chemin from ".DATABASE_TABLE_FOLDER." ORDER BY `name` ASC") or die(mysql_error());
		while ($query = mysql_fetch_array($sql_query) ){
			if ($query['chemin'] == $chemin){
				$_SESSION['error'] = "Chemin déja existant";
				return false;
			}elseif ($query['name'] == $name){
				$_SESSION['error'] = "name déja existant";
				return false;
			}
			if (! Folder::check_name_folder($query['chemin'],$chemin)){
				$_SESSION['error']="Dossier parent ou des dossiers fils sont déja partagé supprimé d'abord les partages qui font conflit";
				return false;
			}
		}
		if (substr($chemin,-1) != "/"){
			$chemin = $chemin."/";
		}
		if (substr($chemin,0,1) != "/"){
			$_SESSION['error']="Le chemin doit être absolu";
		}
		if (! is_dir($chemin)){
			$_SESSION['error']="Dossier invalide ou droit insuffisant";
			return false;
		}
		else{
			mysql_query("INSERT INTO ".DATABASE_TABLE_FOLDER." (id,name,type,chemin)  VALUES(LAST_INSERT_ID() ,'$name','$file_type', '$chemin')");
			return true;
		}
	}
	
	public static function remove_folder($box){
		$tablength = count($box);
		$i = 0;
		while ($i!=$tablength)
		{
			mysql_query("DELETE FROM ".DATABASE_TABLE_FOLDER." WHERE `id` = $box[$i]") or die(mysql_error());
			$i++;
		}
	}	
	
	public static function array_folder(){
		$i=0;
		$sql_query = mysql_query("Select chemin,type from ".DATABASE_TABLE_FOLDER." ORDER BY `name` ASC");
		while ($query = mysql_fetch_array($sql_query)){
			$share_file;
			Folder::check_recurse_folder($query['chemin'],$share_file,$query['type']);
				
		}		
		return serialize($share_file);
	}
	
	public static function check_name_folder($chemin1,$chemin2){
		if(strlen($chemin1)>strlen($chemin2)){
			$count = strlen($chemin2);
		}
		else{
			$count = strlen($chemin1);
		}
		for ($i=0;$i<($count-1);$i++){
			if(substr($chemin1,$i,1) != substr($chemin2,$i,1) ){
				return true;
			}
		}
		return false;
	}
	
	public static function check_recurse_folder($rep,&$share_file,$type=0){
			$dir = opendir($rep);
			$pathrep = $rep;
			while ($file = readdir($dir)) {
				if(is_file($rep.$file)){
					$i = count($share_file);
					//gestion des gros fichiers
					$size = File::GetRealSize($rep.$file);
					//$size =filesize($rep.$file);
					$share_file[$i][0] = $file;
					$share_file[$i][1] = $size;
					$share_file[$i][2] = filectime($rep.$file);
					$share_file[$i][3] = $pathrep.$file;
					$share_file[$i][4] = $type;
				}
				elseif(is_dir($rep.$file) and $file != "." and $file != ".."){
					Folder::check_recurse_folder($rep.$file."/",$share_file,$type);
				}
			}
	}
}	
?>